/**
 * 
 */
package com.huyi.thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 描述：CyclicBarrier样例
 * 
 * @author shengli.hu
 * @since 1.8
 * @version 1.0
 */
public class CyclicBarrierDemo {

	static class Writer extends Thread {
		private CyclicBarrier cyclicBarrier;

		public Writer(CyclicBarrier cyclicBarrier) {
			this.cyclicBarrier = cyclicBarrier;
		}

		@Override
		public void run() {
			System.out.println("线程" + Thread.currentThread().getName() + "正在写入数据...");
			try {
				Thread.sleep(5000); // 以睡眠来模拟写入数据操作
				System.out.println("线程" + Thread.currentThread().getName() + "写入数据完毕，等待其他线程写入完毕");
				cyclicBarrier.await();
				System.out.println(Thread.currentThread().getName() + "所有线程写入完毕，继续处理其他任务...");
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (BrokenBarrierException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws Exception {

		// 次数13：代表通知三次即可
		int len = 3;
		CyclicBarrier barrier = new CyclicBarrier(len);
		
		System.out.println(Thread.currentThread() + "开始启动任务...");
		for(int i=0;i<len;i++) {
			Writer writer = new Writer(barrier);
			writer.setName("t" + i);
			writer.start();
        }
		
	}
}
